package com.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

//大竹哥威武
@Component
public class NettyClient {

    public static String host = "127.0.0.1";
    public static int port = 7891;

    private Channel channel = null;

    @Autowired
    private  NettyClientInitializer nettyClientInitializer;

    @PostConstruct
    public void init() throws InterruptedException, IOException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(nettyClientInitializer);

            // 连接服务端
            channel = b.connect(host, port).sync().channel();

//            this.loop();
        } finally {
//            group.shutdownGracefully();
        }
    }

    public void writeAndFlush(String message){
        channel.writeAndFlush(message + "\r\n");
    }

    public void loop(){
        while(true){
            if(channel.isActive()){
                writeAndFlush("");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
